import React, { useEffect, useState, useRef } from 'react'
import { PageContainer } from '@ant-design/pro-components'
import { useModel, history, useSearchParams } from '@umijs/max'
import { Form, Button, Divider, Input, App, Tree, Checkbox } from 'antd'
import styles from './RoleAddAndEdit.less'

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 }
}

export default () => {
  const { message } = App.useApp()
  const [searchParams] = useSearchParams()
  const { contentWidth, platformType } = useModel('Global')
  const { GetRoleMenu, AddRole, GetEditInfo, UpdateRole } = useModel('RoleList')
  const [formRef] = Form.useForm()
  const [treeData, setTreeData] = useState([])
  const [checkedKeys, setCheckedKeys] = useState([])
  const pageId = Number(searchParams.get('id')) || null

  const [buttonTreeData, setButtonTreeData] = useState([]) // 按钮权限
  const [buttonCheckedKeys, setButtonCheckedKeys] = useState([]) // 按钮权限

  useEffect(() => {
    if (pageId) {
      getEditData()
    }
  }, [])

  // 获取编辑回显数据
  const getEditData = async () => {
    let params = {
      id: pageId
    }
    const res = await GetEditInfo(params)
    formRef.setFieldValue('role_name', res.role_name)

    setCheckedKeys(res.menu_ids.map(item => Number(item)))
    setButtonCheckedKeys(res.button_ids.map(item => Number(item)))
  }

  const handleAddAndEditOk = async () => {
    await formRef.validateFields()
    const values = formRef.getFieldsValue()

    // 判断是否有选中的菜单
    if (!checkedKeys.length) {
      message.error('请选择角色授权')
      return
    }

    let params = {
      ...values,
      menu_ids: checkedKeys,
      id: pageId || null,
      button_ids: buttonCheckedKeys
    }

    // if (platformType === 1) {
    //   params.button_ids = buttonCheckedKeys
    // }

    const res = pageId ? await UpdateRole(params) : await AddRole(params)
    if (res) {
      message.success('操作成功')
    }
  }

  // 获取菜单树
  const getMenuTree = async () => {
    const res = await GetRoleMenu()
    if (res) {
      let temp_menu = [
        {
          id: 10000000,
          menu_name: '全选/取消全选',
          children: res.menus
        }
      ]

      let temp_button = [
        {
          id: 20000000,
          name: '全选/取消全选',
          children: res.buttons
        }
      ]

      setTreeData(temp_menu)
      setButtonTreeData(temp_button)
    }
  }

  // 角色权限
  const handleSelect = (selectedKeys, e) => {
    const { isChild, key } = e.node
    if (isChild) {
      const list = [...checkedKeys]

      const i = list.findIndex(id => id === key)
      if (i !== -1) {
        list.splice(i, 1)
      } else {
        list.push(key)
      }

      setCheckedKeys(list)
    }
  }

  const handleCheck = (checkedKeys, e) => {
    setCheckedKeys(checkedKeys)
  }

  // 按钮权限
  const handleButtonSelect = (selectedKeys, e) => {
    const { isChild, key } = e.node
    if (isChild) {
      const list = [...buttonCheckedKeys]

      const i = list.findIndex(id => id === key)
      if (i !== -1) {
        list.splice(i, 1)
      } else {
        list.push(key)
      }

      setButtonCheckedKeys(list)
    }
  }

  const handleButtonCheck = (checkedKeys, e) => {
    setButtonCheckedKeys(checkedKeys)
  }

  useEffect(() => {
    document.getElementsByClassName('ant-page-header')[0].style.width = `${contentWidth}px`
  }, [contentWidth])

  useEffect(() => {
    getMenuTree()
  }, [])

  return (
    <div className={styles.page_wrapper}>
      <PageContainer
        header={{
          fixedHeader: true,
          title: (
            <div className={styles.header_title}>
              <span>{pageId ? '编辑角色' : '新增角色'}</span>
              <Divider type='vertical' />
              <span className={styles.header_desc}>角色管理页</span>
            </div>
          ),
          extra: [
            <Button key='submit' type='primary' onClick={() => handleAddAndEditOk()}>
              保存
            </Button>
          ]
        }}
      >
        <div className={styles.wrapper}>
          {treeData && treeData.length ? (
            <Form form={formRef} name='form_modal' {...formItemLayout}>
              <Form.Item name='role_name' label='角色名称 : ' rules={[{ required: true, message: '请输入角色名称' }]}>
                <Input placeholder='请输入' allowClear />
              </Form.Item>
              <Form.Item label='角色授权' name='menu_ids' required>
                <Tree
                  checkable
                  treeData={treeData}
                  fieldNames={{ title: 'menu_name', key: 'id', children: 'children' }}
                  defaultExpandAll={true}
                  onSelect={handleSelect}
                  onCheck={handleCheck}
                  checkedKeys={checkedKeys}
                />
              </Form.Item>
              {/* {platformType === 1 ? (
                <>
                  <Form.Item label='按钮权限' required name='button_ids'>
                    <Tree
                      checkable
                      treeData={buttonTreeData}
                      fieldNames={{ title: 'name', key: 'id', children: 'children' }}
                      defaultExpandAll={true}
                      onSelect={handleButtonSelect}
                      onCheck={handleButtonCheck}
                      checkedKeys={buttonCheckedKeys}
                    />
                  </Form.Item>
                </>
              ) : null} */}
              <>
                <Form.Item label='按钮权限' required name='button_ids'>
                  <Tree
                    checkable
                    treeData={buttonTreeData}
                    fieldNames={{ title: 'name', key: 'id', children: 'children' }}
                    defaultExpandAll={true}
                    onSelect={handleButtonSelect}
                    onCheck={handleButtonCheck}
                    checkedKeys={buttonCheckedKeys}
                  />
                </Form.Item>
              </>
            </Form>
          ) : null}
        </div>
      </PageContainer>
    </div>
  )
}
